<?php

namespace App\Http\Controllers\Api\V1\Resources;

use App\Models\BuyerNotice;
use Illuminate\Http\Resources\Json\JsonResource;
use Brick\Math\RoundingMode;
use App\Models\SeckillProduct;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\V1\Resources\ProductResource;

class SeckillProductItemResource extends JsonResource
{
    public function toArray($request)
    {
    	$resource = $this->resource;
    	$nowTime = time();

    	$number = Redis::get(SeckillProduct::seckillProductNumberCacheKey($resource->id));
		$data = [
			'rate'=> 0,
			'seckill_count'=>!empty($number) ? $number : '0',
			'seckill_count_all' =>$resource->seckill_count_all,
			'quota' => $resource->quota,
			'limit' => $resource->limit ? $resource->limit :  $resource->seckill_count_all * 100,
			'saled_at' => $resource->saled_at,
			'sid' =>$resource->id,
			'start_rate' => $resource->start_rate,
			'end_rate' => $resource->end_rate,
			'incr_rate' => $resource->incr_rate,
			'product'=> $resource->product,
			'level' => $resource->level ?? 0,
			

		];

		$data['product']['skus'] = $resource->product->skus;
		$data['product']['images'] = $resource->product->images;
		$data['product']['slides'] = $resource->product->slides;
		if(!empty($data['product']['skus'])){
			foreach($data['product']['skus'] as $k=>$v){

				$data['product']['skus'][$k]['pic_url'] = img_path($data['product']['skus'][$k]['pic']);
			}
		}

		if(!empty($data['product']['images'])){
				foreach($data['product']['images'] as $k=>$v){

					$data['product']['images'][$k]['image_url'] = img_path($data['product']['images'][$k]['image']);
				}
			}
		if(!empty($data['product']['slides'])){
			foreach($data['product']['slides'] as $k=>$v){

				$data['product']['slides'][$k]['slide_url'] = img_path($data['product']['slides'][$k]['slide']);
			}
		}

		
		if($data['seckill_count'] <= 0){

			$data['rate'] = 100; 
		}else{

			$startTime = date("Y-m-d",time()).' '.cs("sale")->start_at;
			$startTime = strtotime($startTime);
			$endTime = date("Y-m-d",time()).' '.cs("sale")->end_at;
			$endTime = strtotime($endTime);


			if($nowTime > $startTime && $nowTime < $endTime){
				$incr = round(($nowTime - $startTime) / $data['incr_rate']);

				$finalRate = $data['start_rate'] + $incr;
				$data['rate'] = $finalRate > $data['end_rate']  ? (int)$data['end_rate'] : (int)$finalRate;

			}
		}

        
        return $data;
    }
}
